/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import entities.Contest;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.User;
import entities.Problem;
import java.util.ArrayList;
import java.util.Collection;
import entities.Submission;

/**
 *
 * @author santiagobaldrich
 */
public class ContestJpaController {

    public ContestJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Contest contest) throws PreexistingEntityException, Exception
    {
        if (contest.getProblemCollection() == null)
        {
            contest.setProblemCollection(new ArrayList<Problem>());
        }
        if (contest.getSubmissionCollection() == null)
        {
            contest.setSubmissionCollection(new ArrayList<Submission>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            User user = contest.getUser();
            if (user != null)
            {
                user = em.getReference(user.getClass(), user.getIdUser());
                contest.setUser(user);
            }
            Collection<Problem> attachedProblemCollection = new ArrayList<Problem>();
            for (Problem problemCollectionProblemToAttach : contest.getProblemCollection())
            {
                problemCollectionProblemToAttach = em.getReference(problemCollectionProblemToAttach.getClass(), problemCollectionProblemToAttach.getIdProblem());
                attachedProblemCollection.add(problemCollectionProblemToAttach);
            }
            contest.setProblemCollection(attachedProblemCollection);
            Collection<Submission> attachedSubmissionCollection = new ArrayList<Submission>();
            for (Submission submissionCollectionSubmissionToAttach : contest.getSubmissionCollection())
            {
                submissionCollectionSubmissionToAttach = em.getReference(submissionCollectionSubmissionToAttach.getClass(), submissionCollectionSubmissionToAttach.getIdSubmission());
                attachedSubmissionCollection.add(submissionCollectionSubmissionToAttach);
            }
            contest.setSubmissionCollection(attachedSubmissionCollection);
            em.persist(contest);
            if (user != null)
            {
                user.getContestCollection().add(contest);
                user = em.merge(user);
            }
            for (Problem problemCollectionProblem : contest.getProblemCollection())
            {
                problemCollectionProblem.getContestCollection().add(contest);
                problemCollectionProblem = em.merge(problemCollectionProblem);
            }
            for (Submission submissionCollectionSubmission : contest.getSubmissionCollection())
            {
                Contest oldContestOfSubmissionCollectionSubmission = submissionCollectionSubmission.getContest();
                submissionCollectionSubmission.setContest(contest);
                submissionCollectionSubmission = em.merge(submissionCollectionSubmission);
                if (oldContestOfSubmissionCollectionSubmission != null)
                {
                    oldContestOfSubmissionCollectionSubmission.getSubmissionCollection().remove(submissionCollectionSubmission);
                    oldContestOfSubmissionCollectionSubmission = em.merge(oldContestOfSubmissionCollectionSubmission);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            if (findContest(contest.getIdContest()) != null)
            {
                throw new PreexistingEntityException("Contest " + contest + " already exists.", ex);
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Contest contest) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest persistentContest = em.find(Contest.class, contest.getIdContest());
            User userOld = persistentContest.getUser();
            User userNew = contest.getUser();
            Collection<Problem> problemCollectionOld = persistentContest.getProblemCollection();
            Collection<Problem> problemCollectionNew = contest.getProblemCollection();
            Collection<Submission> submissionCollectionOld = persistentContest.getSubmissionCollection();
            Collection<Submission> submissionCollectionNew = contest.getSubmissionCollection();
            if (userNew != null)
            {
                userNew = em.getReference(userNew.getClass(), userNew.getIdUser());
                contest.setUser(userNew);
            }
            Collection<Problem> attachedProblemCollectionNew = new ArrayList<Problem>();
            for (Problem problemCollectionNewProblemToAttach : problemCollectionNew)
            {
                problemCollectionNewProblemToAttach = em.getReference(problemCollectionNewProblemToAttach.getClass(), problemCollectionNewProblemToAttach.getIdProblem());
                attachedProblemCollectionNew.add(problemCollectionNewProblemToAttach);
            }
            problemCollectionNew = attachedProblemCollectionNew;
            contest.setProblemCollection(problemCollectionNew);
            Collection<Submission> attachedSubmissionCollectionNew = new ArrayList<Submission>();
            for (Submission submissionCollectionNewSubmissionToAttach : submissionCollectionNew)
            {
                submissionCollectionNewSubmissionToAttach = em.getReference(submissionCollectionNewSubmissionToAttach.getClass(), submissionCollectionNewSubmissionToAttach.getIdSubmission());
                attachedSubmissionCollectionNew.add(submissionCollectionNewSubmissionToAttach);
            }
            submissionCollectionNew = attachedSubmissionCollectionNew;
            contest.setSubmissionCollection(submissionCollectionNew);
            contest = em.merge(contest);
            if (userOld != null && !userOld.equals(userNew))
            {
                userOld.getContestCollection().remove(contest);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld))
            {
                userNew.getContestCollection().add(contest);
                userNew = em.merge(userNew);
            }
            for (Problem problemCollectionOldProblem : problemCollectionOld)
            {
                if (!problemCollectionNew.contains(problemCollectionOldProblem))
                {
                    problemCollectionOldProblem.getContestCollection().remove(contest);
                    problemCollectionOldProblem = em.merge(problemCollectionOldProblem);
                }
            }
            for (Problem problemCollectionNewProblem : problemCollectionNew)
            {
                if (!problemCollectionOld.contains(problemCollectionNewProblem))
                {
                    problemCollectionNewProblem.getContestCollection().add(contest);
                    problemCollectionNewProblem = em.merge(problemCollectionNewProblem);
                }
            }
            for (Submission submissionCollectionOldSubmission : submissionCollectionOld)
            {
                if (!submissionCollectionNew.contains(submissionCollectionOldSubmission))
                {
                    submissionCollectionOldSubmission.setContest(null);
                    submissionCollectionOldSubmission = em.merge(submissionCollectionOldSubmission);
                }
            }
            for (Submission submissionCollectionNewSubmission : submissionCollectionNew)
            {
                if (!submissionCollectionOld.contains(submissionCollectionNewSubmission))
                {
                    Contest oldContestOfSubmissionCollectionNewSubmission = submissionCollectionNewSubmission.getContest();
                    submissionCollectionNewSubmission.setContest(contest);
                    submissionCollectionNewSubmission = em.merge(submissionCollectionNewSubmission);
                    if (oldContestOfSubmissionCollectionNewSubmission != null && !oldContestOfSubmissionCollectionNewSubmission.equals(contest))
                    {
                        oldContestOfSubmissionCollectionNewSubmission.getSubmissionCollection().remove(submissionCollectionNewSubmission);
                        oldContestOfSubmissionCollectionNewSubmission = em.merge(oldContestOfSubmissionCollectionNewSubmission);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = contest.getIdContest();
                if (findContest(id) == null)
                {
                    throw new NonexistentEntityException("The contest with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest contest;
            try
            {
                contest = em.getReference(Contest.class, id);
                contest.getIdContest();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The contest with id " + id + " no longer exists.", enfe);
            }
            User user = contest.getUser();
            if (user != null)
            {
                user.getContestCollection().remove(contest);
                user = em.merge(user);
            }
            Collection<Problem> problemCollection = contest.getProblemCollection();
            for (Problem problemCollectionProblem : problemCollection)
            {
                problemCollectionProblem.getContestCollection().remove(contest);
                problemCollectionProblem = em.merge(problemCollectionProblem);
            }
            Collection<Submission> submissionCollection = contest.getSubmissionCollection();
            for (Submission submissionCollectionSubmission : submissionCollection)
            {
                submissionCollectionSubmission.setContest(null);
                submissionCollectionSubmission = em.merge(submissionCollectionSubmission);
            }
            em.remove(contest);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Contest> findContestEntities()
    {
        return findContestEntities(true, -1, -1);
    }

    public List<Contest> findContestEntities(int maxResults, int firstResult)
    {
        return findContestEntities(false, maxResults, firstResult);
    }

    private List<Contest> findContestEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Contest.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Contest findContest(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Contest.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getContestCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Contest> rt = cq.from(Contest.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public Contest getContestByID(String contestID)
    {
        EntityManager em = null;
        Contest c;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Contest.findByContestID");
            q.setParameter("contestID", contestID);
            c = (Contest) q.getSingleResult();
        } catch (Exception e)
        {
            c = null;
        } finally
        {
            em.clear();
            em.close();
        }
        return c;
    }

    public List<Contest> findAll()
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Contest.findAll");
            return (List<Contest>)q.getResultList();
        } catch (Exception e)
        {
            return null;
        }
    }

    public Contest findContestByName(String contestName)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q= em.createNamedQuery("Contest.findByName");
            q.setParameter("name",contestName);
            return (Contest)q.getSingleResult();
        } catch (Exception e)
        {
            System.out.println("Exception at ContestJPAController.findContestByName: " +e.getMessage());
            return null;
        }
    }
}
